package com.wei.controller.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wei.blog.common.constants.UserConstants;
import com.wei.blog.common.help.UserHelp;
import com.wei.blog.common.utils.R;
import com.wei.entity.UserEntity;
import com.wei.service.UserService;
import com.wei.vo.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController()
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserHelp userHelp;

    @PostMapping("/register")
    R register(@RequestBody UserEntity userEntity) {
        userService.register(userEntity);
        return R.ok();
    }

    /*激活接口*/
    @GetMapping("/activateUser/{code}")
    String activate(@PathVariable String code) {
        if (!ObjectUtils.isEmpty(code)) {
            userService.activateUser(code);
        }
        return null;
    }

    /*登录*/
    @PostMapping("/login")
    R login(@RequestBody UserEntity userEntity, HttpServletResponse response) {
        /*调用登录并存储token*/
        UserToken userToken = userService.login(userEntity.getUsername(), userEntity.getPwd());

        Cookie cookie = new Cookie(UserConstants.TOKEN_COOKIE_KEY, userToken.getToken());

        cookie.setPath("/");

        cookie.setMaxAge(UserConstants.USER_DEFAULE_TIMEOUT);

        response.addCookie(cookie);

        System.out.println(cookie);

        return R.ok();
    }

    @GetMapping("/logout")
    R logOut(@CookieValue(name = UserConstants.TOKEN_COOKIE_KEY, defaultValue = "") String token,
             HttpServletResponse response) {
        userService.logout(token);
        //把浏览器对应的cookie也删除
        Cookie cookie = new Cookie(UserConstants.USER_LOGIN_TOKEN, "");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return R.ok();
    }

    @PostMapping("/password")
    R password(String oldPassword, String newPassword, String newPassword2, HttpServletResponse response) {
        //获取用户的基本信息
        UserToken userToken = userHelp.get();
        //更新密码
        userService.updatePassword(oldPassword, newPassword, newPassword2, userToken);
        //把浏览器对应的cookie也删除
        Cookie cookie = new Cookie(UserConstants.TOKEN_COOKIE_KEY, "");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return R.ok();
    }

}
